/**
 * @time 2018-2-6
 * @description 此模块为选择器的构造函数模块，支持如下属性 isSelectAll/selectedCount/selectedList/list,同时支持全选/全不选/反选操作
 */
define(["knockout"], function (ko) {
    function Selector(list) {
        let self = this;
        if (!ko.isObservableArray(list)) {
            list = ko.observableArray(list);
        }
        self.list = list;
        for (let i = 0; i < list().length; i++) {
            const item = list()[i];
            item.isSelected = ko.observable(false);
        }
        //判断是否是全选操作同时进行对应的显示
        self.isSelectAll = ko.pureComputed({
            read: function () {
                return (
                    self.selectedCount() === self.list().length &&
                    self.list().length !== 0
                );
            },
            write: function (value) {
                if (value) {
                    self.selectAll();
                } else {
                    self.unselectAll();
                }
            },
            // owner: self
        });

        //选中的数量
        self.selectedCount = ko.pureComputed(function () {
            return self.selectedList().length;
        });

        //选中项列表
        self.selectedList = ko.pureComputed(function () {
            return self.list().filter((i) => i.isSelected());
        });
    }

    //反选操作
    Selector.prototype.invertSelect = function () {
        this.list().forEach((e) => e.isSelected(!e.isSelected()));
    };
    //全选
    Selector.prototype.selectAll = function () {
        this.list().forEach((e) => e.isSelected(true));
    };
    //取消全选
    Selector.prototype.unselectAll = function () {
        this.list().forEach((e) => e.isSelected(false));
    };
    if (!window.Selector) {
        window.Selector = Selector;
    }
    return Selector;
});
